package com.guli.acl.helper;

import com.guli.acl.entity.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/6
 */
public class PermissionHelper {

    /**
     * 递归创建菜单 递归入口
     * @param treeNodes
     * @return
     */
    public static List<Permission> build(List<Permission> treeNodes){
        ArrayList<Permission> root = new ArrayList<>();
        for (Permission treeNode : treeNodes) {
            if ("0".equals(treeNode.getPid())){
                treeNode.setLevel(1);
                root.add(findChildren(treeNode, treeNodes));
            }
        }
        return root;
    }

    /**
     * 递归查找子节点
     * @param treeNode
     * @param treeNodes
     * @return
     */
    private static Permission findChildren(Permission treeNode, List<Permission> treeNodes) {
        treeNode.setChildren(new ArrayList<Permission>());
        for (Permission node : treeNodes) {
            // 子节点的id与其子节点pid相等将其放进 其children集合里面去
            // 不相等时递归结束
            if (treeNode.getId().equals(node.getPid())) {
                node.setLevel(treeNode.getLevel() + 1);
                if (treeNode.getChildren() == null){
                    treeNode.setChildren(new ArrayList<Permission>());
                }
                // 放进去
                treeNode.getChildren().add(findChildren(node, treeNodes));
            }
        }
        // 直到没有节点有
        return treeNode;
    }

}
